package com.xsf.jieyou.business.oauth2;

import com.xsf.jieyou.business.common.dto.ResponseResult;
import com.xsf.jieyou.business.common.dto.ResponseStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义 oAuth2 权限不足反馈
 * <p>
 * Description:自定义 oAuth2 错误反馈
 * </p>
 *
 * @author xsf
 * @version v1.0.0
 * @date 2019/11/16 0016
 **/
@Slf4j
@Component("customAccessDeniedHandler")
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response,
                       AccessDeniedException accessDeniedException)
            throws IOException, ServletException {
        response.setStatus(HttpStatus.OK.value());
        response.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        try {
            response.getWriter().write(ResponseResult.build(ResponseStatus.INSUFFICIENT_AUTHORITY.code(),
                    ResponseStatus.INSUFFICIENT_AUTHORITY.message()).toJsonString());
            log.warn("\n[全局业务异常]\r\n异常处理类：{}\r\n异常编码：{}\n异常消息：{}",
                    this.getClass().getName(), ResponseStatus.SERVICE_NOT_FOUND.code(),
                    ResponseStatus.SERVICE_NOT_FOUND.message());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
